package cn.smbms.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.smbms.dao.RoleMapper;
import cn.smbms.pojo.Permission;
import cn.smbms.pojo.User;

//@WebFilter(urlPatterns={"/jsp/*"})
public class SysFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//测试 servlet 容器初始化
		System.out.println("SysFilter init()===========");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// session 验证
		System.out.println("SysFilter doFilter()===========");
		HttpServletRequest rq = (HttpServletRequest)request;
		HttpServletResponse rp = (HttpServletResponse)response;
		User userSession = (User)rq.getSession().getAttribute("userSession");
		if(null == userSession){
			rp.sendRedirect(rq.getContextPath() + "/login");
		}else{
			//继续执行后面操作
			RoleMapper roleMapper = (RoleMapper)WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean("roleMapper");
			List<Permission> permList = roleMapper.getPermissionByRoleId(1);
			request.setAttribute("permList", permList);
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		//测试 servlet 容器销毁
		System.out.println("SysFilter destroy()===========");
	}

}
